import md5 from 'blueimp-md5';
import axios from 'axios';
import * as Device from "../utils/device";
import * as navigation from '../router/navigation';
import rootReducer  from '../redux/reducers';
import { createStore } from 'redux';
import storage from '../utils/storage';

const debug = true; // 上线前改为false
let loginState = false;
export const secretKey = debug ? 'neiwangdekey7267df3ck' : '48976871f26e14b9ff4180769d77937c';

export const apidomain = "customize.shengda-wood.com";

export const fangxinjiadomain = 'api.fangxinjia.cn';

export const request = axios.create({
    baseURL: "",
    method:'POST',
    timeout: 15 * 1000  // 15秒
});

export const ignoreApi = [
    "version/shengda_factory_app",
];


export const setRequestUrl = (url: string) => {
    if (ignoreApi.includes(url)) {
        return `http://${fangxinjiadomain}/${url}`;
    }
    return `http://${apidomain}/${url}`;
}

export const setRequestParams = (data = new Map()) => {
    let sourceValue = '';
    const keysArray = Array.from(data.keys());
    keysArray.sort();
    keysArray.forEach(key => {
        let value = data.get(key);
        sourceValue += value instanceof Array ? "Array" : (value!=null ? value.toString().trim():"");
    });
    data.set('signature', md5(sourceValue == '' ? secretKey : (sourceValue + secretKey)).substring(0, 17));
    const jsonData: any = {};
    data.forEach((v, k) => {
        jsonData[k] = v;
    });
    return jsonData;
}

// 请求拦截器
request.interceptors.request.use(async (config) => {
    const _config: any = config;
    if (_config.url.indexOf('http') == -1) {
      // const store: any = createStore(rootReducer).getState().userInfo;
      let storageUserInfo = await storage.load({ key: "userInfo" }).then((user) => user).catch(() => {}) || {};
      let {user_id, ticket, relationship_id, role_id, token} = storageUserInfo;
      _config.url = setRequestUrl(_config.url);
      if (user_id) {
        _config.data.set('userID', user_id);
      }
      if (ticket) {
        _config.data.set('ticket', ticket);
      }
      if (
        !_config.data.get('factoryID') &&
        relationship_id &&
        _config.url.indexOf('api/v1/factoryOrder/update') == -1 &&
        _config.url.indexOf('api/v1/factoryOrder/list') == -1 &&
        _config.url.indexOf('api/v1/order/list') == -1
      ) {
        _config.data.set('factoryID', relationship_id);
      }
      if (role_id) {
        _config.data.set('roleID', role_id);
      }
      if (token) {
        _config.data.set('token', token);
      }
      _config.data.set('deviceModel', Device.deviceModel || '');
      // _config.data.set("deviceUniqueId", Device.deviceUniqueId || "");
      // _config.data.set("hotUpdateVersion", parseInt(state.hotUpdateVersion) || 0);
      _config.data.set('system', Device.platform);
      if(_config.url.indexOf('api/v1/order/list') == -1){
        _config.data.set('source', 3);
        _config.data.set('source_type', 1);
      }
      _config.data.set('version', Device.appVersion.replace(/\./g, '0'));
      _config.data = setRequestParams(_config.data);
    }
    console.log(_config.url);
    console.log("请求");
    console.log(_config.data);
    console.log("JSON格式");
    console.log(JSON.stringify(_config.data));
    return _config;
});

// 添加响应拦截器
request.interceptors.response.use((response) => {
    // 对响应数据做点什么
    console.log("返回");
    console.log(response.data || {});
    if(response?.data?.code == 40003 && !loginState){
        loginState = true;
        setTimeout(() => {
          navigation && navigation.navigate('Login');
        }, 1000);
        console.log('登录已过期，请重新登录');
        loginState = false;
        return response.data || {}
    }
    return response.data || {};
}, (error) => {
    debugger;
    console.log("出错了");
    console.log(JSON.stringify(error));
    // 对响应错误做点什么
    if (error.request && debug  == false) {
        const { status, responseText } = error.request;
        // 错误提示
    }
    return error.response && error.response.data ? error.response.data : {};
});